package com.cupk.controller;

import com.cupk.pojo.Result;
import com.cupk.pojo.Student;
import com.cupk.pojo.StudentWrapper;
import com.cupk.service.StudentService;
import com.cupk.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    private String appSecret;

    @GetMapping("/isActivation")
    public Result<StudentWrapper> isActivation(@RequestParam String jsCode) {
        String requestStr = "https://api.weixin.qq.com/sns/jscode2session" + "?appid=" + appid + "&secret=" + secret + "&js_code=" + jsCode + "&grant_type=authorization_code";
        Map<String, Object> userWechat = studentService.exchangeVouchers(requestStr);
        String Status = (String) userWechat.get("code");
        // 未能获取到OpenId
        if (Status != null) {
            return Result.error("当前服务不可用！");
        }
        String openid = (String) userWechat.get("openid");
        Student student = studentService.findStudentByOpenid(openid);
        // 当前学生未激活
        if (student == null) {
            return Result.error("当前用户未激活！");
        }
        String token = studentService.generateToken(student);
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token, token, 72, TimeUnit.HOURS);
        StudentWrapper response = new StudentWrapper(token, student);
        return Result.success(response);
    }

    @GetMapping("/exchangeMobile")
    public Result<String> exchangeMobile(@RequestParam String code) {
        if (appSecret == null) {
            appSecret = studentService.getAccessToken(appid, secret);
        }
        Map<String, Object> mobileInfo = studentService.getRealMobile(appSecret, code);
        Integer Status = (Integer) mobileInfo.get("errcode");
        if (Status.equals(40001)) {
            appSecret = studentService.getAccessToken(appid, secret);
            mobileInfo = studentService.getRealMobile(appSecret, code);
            Status = (Integer) mobileInfo.get("errcode");
        }
        if (Status.equals(0)) {
            Map<String, Object> phoneInfo = (Map<String, Object>) mobileInfo.get("phone_info");
            String realPhone = (String) phoneInfo.get("phoneNumber");
            return Result.success(realPhone);
        } else {
            return Result.error("当前服务不可用！");
        }
    }

    @GetMapping("/updateMobile")
    public Result updateMobile(@RequestParam String code) {
        if (appSecret == null) {
            appSecret = studentService.getAccessToken(appid, secret);
        }
        Map<String, Object> map = ThreadLocalUtil.get();
        String stuId = (String) map.get("stuId");
        Map<String, Object> mobileInfo = studentService.getRealMobile(appSecret, code);
        Integer Status = (Integer) mobileInfo.get("errcode");
        if (Status.equals(40001)) {
            appSecret = studentService.getAccessToken(appid, secret);
            mobileInfo = studentService.getRealMobile(appSecret, code);
            Status = (Integer) mobileInfo.get("errcode");
        }
        if (Status.equals(0)) {
            Map<String, Object> phoneInfo = (Map<String, Object>) mobileInfo.get("phone_info");
            String realPhone = (String) phoneInfo.get("phoneNumber");
            studentService.updatePhone(realPhone, stuId);
            return Result.success();
        } else {
            return Result.error("当前服务不可用！");
        }
    }

    @PostMapping("/updateAvatars")
    public Result updateAvatars(@RequestBody Map<String, Object> input){
        String stuId = (String) input.get("stuId");
        String url = (String) input.get("url");
        studentService.updateAvatars(stuId,url);
        return Result.success();
    }

    @PostMapping("/bindingInfo")
    public Result<Student> bindingInfo(@RequestBody Map<String, Object> input) {
        String stuId = (String) input.get("stuId");
        String identityCard = (String) input.get("identityCard");
        Student info = studentService.findStudentByIdentity(stuId, identityCard);
        if (info == null) {
            return Result.error("无法查询到信息！");
        }
        return Result.success(info);
    }

    @PostMapping("/activated")
    public Result activated(@RequestBody Map<String, Object> input) {
        String stuId = (String) input.get("stuId");
        String identityCard = (String) input.get("identityCard");
        String jsCode = (String) input.get("jsCode");
        String phone = (String) input.get("phone");
        Student info = studentService.findStudentByIdentity(stuId, identityCard);
        if (info == null) {
            return Result.error("请求非法！");
        }
        String requestStr = "https://api.weixin.qq.com/sns/jscode2session" + "?appid=" + appid + "&secret=" + secret + "&js_code=" + jsCode + "&grant_type=authorization_code";
        Map<String, Object> userWechat = studentService.exchangeVouchers(requestStr);
        String Status = (String) userWechat.get("code");
        // 未能获取到OpenId
        if (Status != null) {
            return Result.error("当前服务不可用！");
        }
        String openid = (String) userWechat.get("openid"), unionid = (String) userWechat.get("unionid");
        Student judge = studentService.findStudentByStuId(stuId);
        if (judge != null) {
            return Result.error("当前用户已被绑定，请联系管理员处理！");
        }
        studentService.bindingStudent(info.getStuId(), openid, unionid, phone);
        Student updateInfo = studentService.findStudentByStuId(stuId);
        String token = studentService.generateToken(updateInfo);
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token, token, 72, TimeUnit.HOURS);
        return Result.success(token);
    }

    @GetMapping("/studentList")
    public Result<List<Student>> studentList(@RequestParam String query) {
        List<Student> ls = studentService.studentList(query);
        return Result.success(ls);
    }

    @GetMapping("/addBlackList")
    public Result addBlackList(@RequestParam Integer stuId) {
        studentService.setBlackListStatus(stuId, 1);
        return Result.success();
    }

    @GetMapping("/removeBlackList")
    public Result removeBlackList(@RequestParam Integer stuId) {
        studentService.setBlackListStatus(stuId, 0);
        return Result.success();
    }
}
